package cn.lcl.basic.util;
/**
 * 对hibernate相关配置文件进行初始化，然后根据此类来获取session链接
 * @author licho
 *
 */

import cn.lcl.util.ProUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;



public class HibernateInitFactory {
	
	private static Logger log=Logger.getLogger(HibernateInitFactory.class);
	
	private static Configuration config;
	
	private static SessionFactory factory;
	
	private static final String DEFAULT_CONFIG= "hibernate/hibernate.cfg.xml";
	
	static{
		//加載主配置文件
		final String config= ProUtils.getProperty("hibernate.configPath");
		System.out.println(config);
		final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
				.configure(config==null ? DEFAULT_CONFIG :config).build();
		try{
			factory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
		}catch(Exception e){
			//registry本能够被SessionFactory自动销毁的，但是这里我们创建SessionFactory失败，所以
			//我们手动销毁
			StandardServiceRegistryBuilder.destroy(registry);
			log.error("factory 工厂构建失败！", e);
		}
	}
	
	public static void main(String[] args) {
		Session session=getTranstionSession();
		
//		try{
//			session.beginTransaction();//开启事务
//			Student stu=new Student("李崇林",true,"123456");
//			stu.setEmail("582772459@qq.com");
//			stu.setPhone("17770030629");
//			session.save(stu);//插入操作
//			stu.setName("lichonglin");
//			session.saveOrUpdate(stu);//更新操作，id为null时插入，id不为空时，执行更新操作，id在DB不存在时，抛出异常
//			Student getStu=session.get(Student.class,stu.getId());//根据主键查找，查找不到时会抛出异常
//			System.out.println("获取的stu INFO："+getStu);
//			try{
//				Student loadStu=session.load(Student.class, 150L);//根据主键查找，查找不到会抛出异常
//				System.out.println(loadStu);
//			}catch (Exception e) {
//				// TODO: handle exception
//				log.error("load方法找不到会抛出异常");
//			}
//			session.delete(stu);//根据id删除student,删除id为144L的记录
//			session.getTransaction().commit();//提交
//			System.out.println(stu.getId());
//		}catch (Exception e) {
//			// TODO: handle exception
//			session.getTransaction().rollback();//发生异常进行回滚
//			log.error("数据库插入失败", e);
//		}
	}
	
	/**
	 * 获得一个session，每次调用开启一个新的session
	 * @return
	 */
	public static Session getSession(){
		if(factory==null||factory.isClosed()){
			factory=new Configuration().configure("hibernate/hibernate.cfg.xml").buildSessionFactory();
		}
		return factory.openSession();
	}
	/**
	 * 每个线程对应同一session,获取当前线程的Session
	 * @return
	 */
	public static Session getTranstionSession(){
		if(factory==null||factory.isClosed()){
			factory=new Configuration().configure("hibernate/hibernate.cfg.xml").buildSessionFactory();
		}
		return factory.getCurrentSession();
	}
	
	
}
